package ui.activity.homepage;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dispatchapp.andlei.R;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.GoodsListAdapter;
import adapter.OrderDetailAdapter;
import base.BaseBean;
import base.activity.BaseLayoutActivity;
import bean.OrderDetailBean;
import bean.TestBean;
import netWork.NetUtils;
import utils.CodeUtils;
import utils.DensityUtil;
import utils.GsonUtils;
import utils.SPUtils;
import utils.TimerUtil;
import widget.DetailPopupWindow;
import widget.ShopStatusPopupWindow;

/**
 * 订单详情
 *
 * @author Andlei
 * @DATE 2019/1/28
 */
public class OrderDetailActivity extends BaseLayoutActivity {
    private NetUtils netUtils;
    private TextView tv_id;
    private TextView tv_time, tv_money, tv_detail;
    private TextView tv_address1, tv_address2;
    private TextView tv_order_code, tv_shouhuo, tv_remark, tv_total, tv_rider_inshcool, tv_rider_outshcool, tv_dispatch,tv_peisong;
    private ImageView img_copy, img_gaipai_inschool, img_gaipai_outschool,img_code;
    private TextView tv_rider_inschool_phone, tv_rider_outschool_phone, tv_dispatch_phone;
    private RecyclerView recyclerView;
    private RecyclerView list_rcy_goods;
    private ShopStatusPopupWindow pop;
    private DetailPopupWindow dpop;
    private View mView;
    private TextView tv_yichang, tv_callphone ,tv_send_message, tv_send_phone;
    private String order_no;
    private String shangjia_phone;
    private String tongxue_phone;
    private String tongxue_phone2;
    private String status ="";
//    private int end_time = 0;
    private OrderDetailAdapter adapter;
    private GoodsListAdapter goodsListAdapter;
    private List<TestBean> list = new ArrayList<>();
    private OrderDetailBean.MoneyListBean moneyListBean;
    private List<OrderDetailBean.GoodsListBean> goodsListBeanList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView = getWindow().getDecorView();
        setTitle("订单详情", true);
       setTitlefontBg_black();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void findViews() {
        netUtils = new NetUtils(mActivity, netRequestCallBack);
        tv_id = getView(R.id.tv_id);
        tv_time = getView(R.id.tv_time);
        tv_money = getView(R.id.tv_money);
        tv_detail = getView(R.id.tv_detail);
        tv_address1 = getView(R.id.tv_address1);
        tv_address2 = getView(R.id.tv_address2);
        tv_order_code = getView(R.id.tv_order_code);
        tv_peisong = getView(R.id.tv_peisong);
        tv_shouhuo = getView(R.id.tv_shouhuo);
        tv_remark = getView(R.id.tv_remark);
        tv_total = getView(R.id.tv_total);
        tv_rider_inshcool = getView(R.id.tv_rider_inshcool);
        tv_rider_outshcool = getView(R.id.tv_rider_outshcool);
        tv_dispatch = getView(R.id.tv_dispatch);
        img_copy = getView(R.id.img_copy);
        img_gaipai_inschool = getView(R.id.img_gaipai_inschool);
        img_gaipai_outschool = getView(R.id.img_gaipai_outschool);
        img_code = getView(R.id.img_code);
        tv_rider_inschool_phone = getView(R.id.tv_rider_inschool_phone);
        tv_rider_outschool_phone = getView(R.id.tv_rider_outschool_phone);
        tv_dispatch_phone = getView(R.id.tv_dispatch_phone);
        recyclerView = getView(R.id.list_rcy);
        list_rcy_goods = getView(R.id.list_rcy_goods);
//        tv_yichang = getView(R.id.tv_yichang);
        tv_callphone = getView(R.id.tv_callphone);

        tv_send_message = getView(R.id.tv_send_message);
        tv_send_phone = getView(R.id.tv_send_phone);
    }

    @Override
    protected void formatViews() {
        tv_detail.setOnClickListener(this);
        img_copy.setOnClickListener(this);
        img_gaipai_inschool.setOnClickListener(this);
        img_gaipai_outschool.setOnClickListener(this);
        tv_rider_inschool_phone.setOnClickListener(this);
        tv_rider_outschool_phone.setOnClickListener(this);
        tv_dispatch_phone.setOnClickListener(this);
//        tv_yichang.setOnClickListener(this);
        tv_callphone.setOnClickListener(this);
        tv_send_message.setOnClickListener(this);
        tv_send_phone.setOnClickListener(this);
        if(SPUtils.getInstance(mActivity).getString("Is_coach").equals("2")){
            if(!status.equals("delivery")){
                img_gaipai_inschool.setVisibility(View.VISIBLE);
                img_gaipai_outschool.setVisibility(View.VISIBLE);
            }
        }else {
            img_gaipai_inschool.setVisibility(View.GONE);
            img_gaipai_outschool.setVisibility(View.GONE);
        }
        TestBean bean = new TestBean();
        TestBean bean1 = new TestBean();
        TestBean bean2 = new TestBean();
        TestBean bean3 = new TestBean();
        TestBean bean4 = new TestBean();
        bean.str = "用户下单";
        bean1.str = "商家接单";
        bean2.str = "到达中转";
        bean3.str = "用户取餐";
        bean4.str = "订单完成";
        list.add(bean);
        list.add(bean1);
        list.add(bean2);
        list.add(bean3);
        list.add(bean4);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayout.HORIZONTAL);
        switch (status){
            case "paid":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,1);
                break;
            case "received_order":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,1);
                break;
            case "take_food":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,2);
                break;
            case "sark":
            case "transfer":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,3);
                break;
            case "distributing":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,4);
                break;
            case "delivery":
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,5);
                break;
            default:
                adapter = new OrderDetailAdapter(R.layout.item_order_detail,list,3);
                break;
        }
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        LinearLayoutManager goodlayoutManager = new LinearLayoutManager(mActivity);
        goodlayoutManager.setOrientation(LinearLayout.VERTICAL);
        goodsListAdapter = new GoodsListAdapter(R.layout.item_goodslist,goodsListBeanList);
        list_rcy_goods.setLayoutManager(goodlayoutManager);
        list_rcy_goods.setAdapter(goodsListAdapter);

    }

    /**
     *配送区域 - 发送订单通知
     */
    private void SendMsgorCall(Integer type){
        Map<String, Object> map = new HashMap<>();
        map.put("order_no", order_no);
        //type 	Int 1:短信， 2:电话
        map.put("type",""+type);
        netUtils.get("rider/user/send-order-msg", map, BaseBean.class, null, false);
    }

    @Override
    protected void formatData() {
        Map<String, Object> map = new HashMap<>();
        map.put("order_no", order_no);
        netUtils.get("rider/user/order", map, BaseBean.class, null, false);
    }

    @Override
    protected void getBundle(Bundle bundle) {
        status = bundle.getString("status");
        order_no = bundle.getString("order_no");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_detail:
                //收入明细
                if(dpop == null){
                    dpop = new DetailPopupWindow(OrderDetailActivity.this,moneyListBean);
                    dpop.showAsDropDown(tv_detail, DensityUtil.dip2px(mActivity,-80),0);
                }else {
                    dpop.showAsDropDown(tv_detail,DensityUtil.dip2px(mActivity,-80),0);
                }
                break;
            case R.id.img_copy:
                //复制
                ClipboardManager cm = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                    cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                }
                cm.setText(order_no);
                toast("已复制");
                break;
            case R.id.img_gaipai_inschool:
                //校内改派
                Bundle bundle = new Bundle();
                bundle.putString("type","1");
                bundle.putString("order_no",""+order_no);
                jumpTo(DispatchRiderActivity.class,bundle);
                break;
            case R.id.img_gaipai_outschool:
                //校外改派
                Bundle cbundle = new Bundle();
                cbundle.putString("type","2");
                cbundle.putString("order_no",""+order_no);
                jumpTo(DispatchRiderActivity.class,cbundle);
                break;
            case R.id.tv_rider_inschool_phone:
                //校内骑手电话
                callPhone(tv_rider_inschool_phone.getText().toString());
                break;
            case R.id.tv_rider_outschool_phone:
                //校外骑手电话
                callPhone(tv_rider_outschool_phone.getText().toString());
                break;
            case R.id.tv_dispatch_phone:
                //调配员电话
                callPhone(tv_dispatch_phone.getText().toString());
                break;
//            case R.id.tv_yichang:
//                //异常处理
//                break;
            case R.id.tv_send_message:
                // 发送短信提醒
                SendMsgorCall(1);
                break;
            case R.id.tv_send_phone:
                // 发送语音电话
                SendMsgorCall(2);
                break;
            case R.id.tv_callphone:
                //拨打电话
                if(pop == null){
                    pop = new ShopStatusPopupWindow(OrderDetailActivity.this,new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if(view.getId() == R.id.tv_open){
                                callPhone(shangjia_phone);
                            }else if(view.getId() == R.id.tv_close){
                                CallPhoneNumber(order_no,1); //1:用户电话， 2:用户备用电话
//                                callPhone(tongxue_phone);
                            }else if(view.getId() == R.id.tv_third){
                                CallPhoneNumber(order_no,2);
//                                callPhone(tongxue_phone2);
                            }
                            pop.dismiss();

                        }
                    });
                    pop.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,0);
                }else {
                    pop.showAtLocation(mView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,0);
                }
                break;
        }
    }

    private NetUtils.NetRequestCallBack netRequestCallBack = new NetUtils.NetRequestCallBack() {
        @Override
        public void error(String action, Throwable e, Map tag) {
        }

        @Override
        public void success(String action, BaseBean t, Map tag) {
            switch (action){
                case "rider/user/send-order-msg":
                    if (t.getCode() != 200) {
                        toast(t.getMsg());
                    } else {
                        toast("发送提醒成功");
                    }
                    break;
                case "notice/order-call":
                    if (t.ok != 1) {
                        toast(t.getMsg());
                    } else {
                        callPhone(t.getCall_number());
                    }
                    break;
                default:
                    OrderDetailBean bean = (OrderDetailBean) GsonUtils.getInstance(mActivity).parseComplexJArrayByCommon(t, OrderDetailBean.class);
                    initData(bean);
                    break;
            }

        }
    };

    private void initData(OrderDetailBean bean) {
        tv_id.setText("#"+bean.getOrder_num());
        int end_time = bean.getEnd_time();
        int mint = Integer.parseInt(bean.getTime_used())/60;
//        if(stime>600){
//            tv_time.setText(">600分钟");
//        }else {
//            tv_time.setText(stime+"分钟");
//        }
        if(end_time == 0){
            if(mint<20){
                tv_time.setText(mint+"分钟");
                tv_time.setTextColor(Color.parseColor("#999999"));
            }else if(20<=mint&&mint<40){
                tv_time.setText(mint+"分钟");
                tv_time.setTextColor(Color.parseColor("#3AB335"));
            }else if(40<=mint&&mint<=60){
                tv_time.setText(mint+"分钟");
                tv_time.setTextColor(Color.parseColor("#FF9F1D"));
            }else if(60<mint&&mint<600){
                tv_time.setText(mint+"分钟");
                tv_time.setTextColor(Color.parseColor("#EA1D11"));
            }else {
                tv_time.setText(">600分钟");
                tv_time.setTextColor(Color.parseColor("#EA1D11"));
            }
            Spannable span = new SpannableString(tv_time.getText());
            span.setSpan(new AbsoluteSizeSpan(35), tv_time.getText().length()-2, tv_time.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            tv_time.setText(span);
        }else {
            int msint = (end_time/60)+1;
            if(end_time>0){
                tv_time.setText(TimerUtil.timedate(bean.getWill_send_time()) +"送达");
                tv_id.setBackgroundColor(Color.parseColor("#FFB949"));
                        //setBackgroundColor(R.id.tv_id,Color.parseColor("#FFB949"));
                tv_time.setTextColor(Color.parseColor("#FFB949"));
                Spannable span = new SpannableString(tv_time.getText());
                span.setSpan(new AbsoluteSizeSpan(35), tv_time.getText().length()-2, tv_time.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_time.setText(span);
            }else {
                if(Math.abs(msint)>600){
                    tv_time.setText("已超时>600分钟");
                    Spannable span = new SpannableString(tv_time.getText());
                    span.setSpan(new AbsoluteSizeSpan(35), tv_time.getText().length()-2, tv_time.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new AbsoluteSizeSpan(35), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_time.setText(span);
                }else {
                    tv_time.setText("已超时"+Math.abs(msint)+"分钟");
                    Spannable span = new SpannableString(tv_time.getText());
                    span.setSpan(new AbsoluteSizeSpan(35), tv_time.getText().length()-2, tv_time.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    span.setSpan(new AbsoluteSizeSpan(35), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_time.setText(span);
                }
                tv_id.setBackgroundColor(Color.parseColor("#FFB949"));
                tv_time.setTextColor(Color.parseColor("#EA1D11"));
            }
            tv_peisong.setText("预订单");
        }
        tv_money.setText(bean.getMoney()+"元");
        Spannable mspan = new SpannableString(tv_money.getText());
        mspan.setSpan(new AbsoluteSizeSpan(35), tv_money.getText().length()-1, tv_money.getText().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_money.setText(mspan);
        tv_address1.setText(bean.getStudent_name()+"("+bean.getAddr_sex()+")"+"-"+bean.getAddress());
        tv_address2.setText(bean.getStore_name()+"-"+bean.getStore_address());
        img_code.setImageBitmap(CodeUtils.createBarcode(bean.getOrder_no(),DensityUtil.dip2px(400),DensityUtil.dip2px(80)));
        tv_order_code.setText(Html.fromHtml("<font color='#999999'>订 单 号：</font>"+"<font color='#333333'>"+bean.getOrder_no()+"</font>"));
        tv_shouhuo.setText(Html.fromHtml("<font color='#999999'>收 货 人：</font>"+"<font color='#333333'>"+bean.getStudent_name()+"</font>"));
        tv_remark.setText(Html.fromHtml("<font color='#999999'>备 注：</font>"+"<font color='#333333'>"+bean.getRemark()+"</font>"));
        tv_total.setText(Html.fromHtml("<font color='#999999'>合 计：</font>"+"<font color='#333333'>"+bean.getPay_price()+"</font>"));
        tv_rider_inshcool.setText(Html.fromHtml("<font color='#999999'>送餐骑手：</font>"+"<font color='#333333'>"+bean.getSchool_rider_name()+"</font>"));
        tv_rider_inschool_phone.setText(bean.getSchool_rider_phone());
        tv_rider_outshcool.setText(Html.fromHtml("<font color='#999999'>取餐骑手：</font>"+"<font color='#333333'>"+bean.getOut_rider_name()+"</font>"));
        tv_rider_outschool_phone.setText(bean.getOut_rider_phone());
        tv_dispatch.setText(Html.fromHtml("<font color='#999999'>调 度 员：</font>"+"<font color='#333333'>"+bean.getRider_name()+"</font>"));
        tv_dispatch_phone.setText(bean.getRider_phone());
        shangjia_phone = bean.getStore_phone();
        tongxue_phone = bean.getStudent_phone();
        tongxue_phone2 = bean.getBak_phone();
        moneyListBean =  bean.getMoney_list();
        goodsListBeanList = bean.getGoods_list();
        goodsListAdapter.setNewData(goodsListBeanList);
        if(!TextUtils.isEmpty(bean.getPay_time())&&bean.getPay_time().length()>8){
            list.get(0).time = bean.getPay_time().substring(bean.getPay_time().length()-8,bean.getPay_time().length()-3);
        }
        if(!TextUtils.isEmpty(bean.getStore_begin_time())&&bean.getStore_begin_time().length()>8){
            list.get(1).time = bean.getStore_begin_time().substring(bean.getStore_begin_time().length()-8,bean.getStore_begin_time().length()-3);
        }
        if(!TextUtils.isEmpty(bean.getDispatch_time())&&bean.getDispatch_time().length()>8){
            list.get(2).time = bean.getFinish_dispatch().substring(bean.getDispatch_time().length()-8,bean.getDispatch_time().length()-3);
        }
        if(!TextUtils.isEmpty(bean.getFinish_time())&&bean.getFinish_time().length()>8){
            list.get(3).time = bean.getFinish_time().substring(bean.getFinish_time().length()-8,bean.getFinish_time().length()-3);
        }
       // list.get(0).time = bean.getPay_time();
//        list.get(1).time = bean.getStore_begin_time();
//        list.get(2).time = bean.getDispatch_time();
//        list.get(3).time = bean.getFinish_time();
        list.get(4).time = "";
        switch (status){
            case "paid":
                list.get(0).isSelect = true;
               // list.get(1).isSelect = true;
                break;
            case "received_order":
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                break;
            case "take_food":
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                break;
            case "sark":
            case "transfer":
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                list.get(2).isSelect = true;
                break;
            case "distributing":
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                list.get(2).isSelect = true;
                list.get(3).isSelect = true;
                break;

            case "delivery":
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                list.get(2).isSelect = true;
                list.get(3).isSelect = true;
                list.get(4).isSelect = true;
                break;
            default:
                list.get(0).isSelect = true;
                list.get(1).isSelect = true;
                list.get(2).isSelect = true;
                break;
        }
        adapter.notifyDataSetChanged();
        //tv_time.setText();
    }
    /**
     * 拨打电话（直接拨打电话）
     *
     * @param phoneNumber 电话号码
     */
    @SuppressLint("MissingPermission")
    public void  callPhone(final String phoneNumber) {
        if (mActivity == null || android.text.TextUtils.isEmpty(phoneNumber)) {
            return;
        }
        if(phoneNumber.length() < 8 || phoneNumber.length() > 11){
            toast("电话号码格式或输入有误");
            return;
        }
        //6.0权限处理
        Acp.getInstance(mActivity).request(new AcpOptions.Builder().setPermissions(
                Manifest.permission.CALL_PHONE).build(), new AcpListener() {
            @SuppressLint("MissingPermission")
            @Override public void onGranted() {
                Uri u = Uri.parse("tel:" + phoneNumber);
                Intent it = new Intent(Intent.ACTION_CALL, u);
                mActivity.startActivity(it);
            }
            @Override public void onDenied(List<String> permissions) {
            }
        });
    }

    private void CallPhoneNumber(String order_no ,Integer type){
        Map<String, Object> map = new HashMap<>();
        map.put("order_no", order_no);
        map.put("type", type); //1:用户电话， 2:用户备用电话
        netUtils.postNew("notice/order-call", map, BaseBean.class,false);
    }
}
